<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="queryParams" @keyup.enter="handleQuery">
        <el-form-item label="文章标题">
          <el-input v-model="queryParams.title" placeholder="请输入文章标题" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="queryParams.categoryId" placeholder="请选择分类" style="width: 150px" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 150px" clearable>
            <el-option label="草稿" :value="0" />
            <el-option label="已发布" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-container" shadow="never">
      <template #header>
        <div class="header-operations">
          <el-button type="primary" @click="handleAdd">新增文章</el-button>
          <el-button @click="handleCategory">分类管理</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="articleList">
        <el-table-column label="标题" prop="title" show-overflow-tooltip />
        <el-table-column label="分类" width="100">
          <template #default="{ row }">
            <el-tag>{{ getCategoryName(row.categoryId) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="浏览量" prop="viewCount" width="300" align="center" />
        <el-table-column label="状态" width="150" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="220" />
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="success"
              link
              @click="handlePublish(scope.row)"
            >发布</el-button>
            <el-button type="primary" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #total>
            共计 {{ total }} 条
          </template>
          <template #sizes>
            <el-select v-model="queryParams.size" style="width: 110px">
              <el-option
                v-for="item in [10, 20, 30, 50]"
                :key="item"
                :label="`${item}条/页`"
                :value="item"
              />
            </el-select>
          </template>
        </el-pagination>
      </div>
    </el-card>

    <!-- 分类管理弹窗 -->
    <category-dialog
      v-if="categoryDialog.visible"
      v-model:visible="categoryDialog.visible"
      @success="handleCategorySuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { getArticleList, deleteArticle, publishArticle } from '@/api/article'
import { getCategoryList, addCategory, updateCategory, deleteCategory } from '@/api/articleCategory'
import CategoryDialog from './components/CategoryDialog.vue'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  title: '',
  categoryId: undefined,
  status: undefined
})

// 数据列表
const loading = ref(false)
const total = ref(0)
const articleList = ref([])
const categoryOptions = ref([])
const categoryList = ref([])

// 分类管理弹窗
const categoryDialog = reactive({
  visible: false
})

// 获取文章列表
const getList = async () => {
  try {
    loading.value = true
    const { data } = await getArticleList(queryParams)
    articleList.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const getCategories = async () => {
  try {
    const { data } = await getCategoryList()
    categoryOptions.value = data.records
    categoryList.value = data.records
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  const category = categoryOptions.value.find(item => item.id === categoryId)
  return category ? category.name : '未分类'
}

// 查询操作
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.title = ''
  queryParams.categoryId = undefined
  queryParams.status = undefined
  handleQuery()
}

// 新增文章
const handleAdd = () => {
  router.push('/article/edit')
}

// 编辑文章
const handleEdit = (row) => {
  router.push(`/article/edit/${row.id}`)
}

// 预览文章
const handlePreview = (row) => {
  router.push(`/article/preview/${row.id}`)
}

// 删除文章
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该文章吗?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteArticle(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 发布文章
const handlePublish = (row) => {
  ElMessageBox.confirm('确认要发布该文章吗?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await publishArticle(row.id)
      ElMessage.success('发布成功')
      getList()
    } catch (error) {
      console.error('发布失败:', error)
    }
  })
}

// 打开分类管理
const handleCategory = () => {
  categoryDialog.visible = true
}

// 分类管理成功回调
const handleCategorySuccess = () => {
  getCategories()
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.size = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.current = val
  getList()
}

onMounted(() => {
  getList()
  getCategories()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .header-operations {
    display: flex;
    gap: 10px;
  }
}
</style>
